home *** CD-ROM | disk | FTP | other *** search
/ Megaware 1 / Megaware Volume 1.iso / programg / c-tutor / chap04.txt < prev    next >
Text File  |  1990-07-20  |  22KB  |  473 lines

  1.  
  2.  
  3.  
  4.                                                         Chapter 4
  5.                                                         FUNCTIONS
  6.  
  7. This chapter discusses the changes in the use of functions that
  8. have been made to C++ in order to make programming more convenient
  9. and to let the compiler do further checking for errors.  A fair
  10. amount of time is also spent on teaching the modern form of
  11. function definition and prototyping.
  12.  
  13. Prototyping allows the compiler to do additional type checking for
  14. your function calls which can aid in detecting programming errors. 
  15. The first two example programs in this chapter are designed to
  16. teach prototyping and what it will do for you.  Prototyping is a
  17. relatively new addition to C, so even some experienced C
  18. programmers are not familiar with it.  If you have experience with
  19. prototyping you can skip directly to the section named INLINE CODE
  20. on page 4-4 of this chapter.
  21.  
  22.  
  23. PROTOTYPES
  24. _________________________________________________________________
  25.  
  26. Examine the file named PROTYPE1.CPP for our      ================
  27. first look at a prototype and an illustration of   PROTYPE1.CPP
  28. how it is used.  The prototyping used in C++ is  ================
  29. no different than that used in ANSI-C. 
  30. Actually, many C programmers take a rather dim
  31. view of prototyping and seem reluctant to use it, but with C++ it
  32. is considerably more important and is in much heavier use.  In
  33. fact, prototyping is required to be used in C++.
  34.  
  35. A prototype is a limited model of a more complete entity to come
  36. later.  In this case, the full function is the complete entity to
  37. come later and the prototype is illustrated in line 4.  The
  38. prototype gives a model of the interface to the function that can
  39. be used to check the calls to the function for the proper number
  40. of parameters and the correct types of parameters.  Each call to
  41. the function named do_stuff() must have exactly three parameters
  42. or the compiler will give an error message.  In addition to the
  43. correct number of parameters, the types must be compatible or the
  44. compiler will issue an error message.  Notice that when the
  45. compiler is working on lines 12 and 13, the type checking can be
  46. done based on the prototype in line 4 even though the function
  47. itself is not yet defined.  If the prototype is not given, the
  48. number of parameters will not be checked, nor will the types of the
  49. parameters be checked.  You will get an apparently good compile and
  50. link, but the program may do some very strange things when it is
  51. executed if the correct number of parameters are not used.
  52.  
  53. To write the prototype, simply copy the header from the function
  54. to the beginning of the program and append a semicolon to the end
  55. as a signal to the compiler that this is not a function but a
  56. prototype.  The variable names given in the prototype are optional
  57.  
  58.                                                          Page 4-1
  59.  
  60.                                             Chapter 4 - Functions
  61.  
  62. and act merely as comments to the program reader since they are
  63. completely ignored by the compiler.  You could replace the variable
  64. name wings in line 4 with your first name and there would be no
  65. difference in compilation.  Of course, the next person that had to
  66. read your program would be somewhat baffled with your choice of
  67. names.
  68.  
  69. In this case, the two function calls to this function, given in
  70. lines 12 and 13, are correct so no error will be listed during
  71. compilation.
  72.  
  73. Even though we wish to use the char type for eyes in the function,
  74. we wish to use it as a number rather than as a character.  The cast
  75. to int in line 20 is required to force the printout of the
  76. numerical value rather than an ASCII character.  The next example
  77. program is similar but without the cast to int.
  78.  
  79.  
  80. COMPATIBLE TYPES
  81. _________________________________________________________________
  82.  
  83. We mentioned compatible types earlier so we should review them just
  84. a bit in order to make our discussion of prototyping complete. 
  85. Compatible types are any simple types that can be converted from
  86. one to another in a meaningful way.  For example, if you used an
  87. integer as the actual parameter and the function was expecting a
  88. float type as the formal parameter, the system would do the
  89. conversion automatically, without mentioning it to you.  This is
  90. also true of a float changing to a char, or a char changing to an
  91. int.  There are definite conversion rules which would be followed. 
  92. These rules are given in great detail in section 3.2 of the draft
  93. of the ANSI-C standard and are also given on page 198 of the second
  94. edition of the K&R reference.
  95.  
  96. If we supplied a pointer to an integer as the actual parameter and
  97. expected an integer as the formal parameter in the function, the
  98. conversion would not be made because they are two entirely
  99. different kinds of values.  Likewise, a structure would not be
  100. converted automatically to a long float, an array, or even to a
  101. different kind of structure, they are all incompatible and cannot
  102. be converted in any meaningful manner.  The entire issue of type
  103. compatibility as discussed in chapter 2 of this tutorial applies
  104. equally well to the compatibility of types when calling a function. 
  105. Likewise, the type specified as the return type, in this case void,
  106. must be compatible with the expected return type in the calling
  107. statement, or the compiler will issue a warning.
  108.  
  109.  
  110. HOW DOES PROTOTYPING WORK?
  111. _________________________________________________________________
  112.  
  113. This is your chance to try prototyping for yourself and see how
  114. well it works and what kinds of error messages you get when you do
  115. certain wrong things.  Change the actual parameters in line 12 to
  116.  
  117.                                                          Page 4-2
  118.  
  119.                                             Chapter 4 - Functions
  120.  
  121. read (12.2, 13, 12345) and see what the compiler says about that
  122. change.  It will probably say nothing because they are all type
  123. compatible.  If you change it to read (12.0, 13), it will issue a
  124. warning or error because there are not enough arguments given. 
  125. Likewise you should receive an error message if you change one of
  126. the parameters in line 13 to an address by putting an ampersand in
  127. front of one of the variable names.  Finally, change the first word
  128. in line 4 from void to int and see what kind of error message is
  129. given.  You will first be required to make the function header in
  130. line 16 agree with the prototype, then you will find that there is
  131. not a variable returned from the function.  Finally, you will find
  132. that there is a returned value that is not used in the calling
  133. program.  You should have a good feeling that prototyping is doing
  134. something good for you after making all of those changes.
  135.  
  136. Be sure to compile and execute this program then make the changes
  137. recommended above, attempting to compile it after each change.
  138.  
  139.  
  140. A LITTLE MORE PROTOTYPING
  141. _________________________________________________________________
  142.  
  143. Examine the next example program named           ================
  144. PROTYPE2.CPP for a little more information on      PROTYPE2.CPP
  145. prototyping.  This program is identical to the   ================
  146. last one except for a few small changes.  The
  147. variable names have been omitted from the
  148. prototype in line 4 merely as an illustration that they are
  149. interpreted as comments by the C++ compiler.  The function header
  150. is formatted differently to allow for a comment alongside each of
  151. the actual parameters.  This should make the function header a
  152. little more self explanatory.  However, you should remember that
  153. comments should not be used to replace good selection of variable
  154. names.  In this particular case, the comments add essentially
  155. nothing to the clarity of the program.
  156.  
  157.  
  158.  
  159. WHAT DOES PROTOTYPING COST?
  160. _________________________________________________________________
  161.  
  162. Prototyping is essentially free because it costs absolutely nothing
  163. concerning the run time size or speed of execution.  Prototyping
  164. is a compile time check and slows down the compile time a
  165. negligible amount because of the extra checking that the compiler
  166. must do.  If prototyping finds one error for you that you would
  167. have had to find with a debugger, it has more than paid for itself
  168. for use in an entire project.  I once spent 12 hours of debugging
  169. time to find that I forgot to pass the address of a variable to a
  170. function.  Prototyping would have found the error on the first
  171. compilation of this 2000 line program.
  172.  
  173. The only price you pay to use prototyping is the extra size of the
  174. source files because of the prototypes, and the extra time for the
  175.  
  176.                                                          Page 4-3
  177.  
  178.                                             Chapter 4 - Functions
  179.  
  180. compiler to read the prototypes during the compilation process, but
  181. both costs are negligible.
  182.  
  183. Be sure to compile and execute this example program.  You will find
  184. that it is identical to the last example program.
  185.  
  186.  
  187.  
  188. PASS BY REFERENCE
  189. _________________________________________________________________
  190.  
  191. Examine The file named PASSREF.CPP for an          ===============
  192. example of a pass by reference, a construct          PASSREF.CPP
  193. which is not available in ANSI-C.  The reference   ===============
  194. variable was mentioned in chapter 1 and it was
  195. recommended there that you don't use it.  This
  196. example program illustrates where it can be used to your advantage. 
  197. The pass by reference allows the passing of a variable to a
  198. function and returning the changes made in the function to the main
  199. program.  In ANSI-C the same effect can be seen when a pointer to
  200. a variable is passed to a function, but this is a little neater.
  201.  
  202. Observe the prototype in line 4 where the second variable has an
  203. ampersand in front of the variable name.  The ampersand instructs
  204. the compiler to treat this variable just like it were passed a
  205. pointer to the variable since the actual variable from the main
  206. program will be used in the function.  In the function itself, in
  207. lines 21 through 24, the variable in2 is used just like any other
  208. variable but we are using the variable passed to this function from
  209. the main program not a copy of it.  The other variable named in1
  210. is treated just like any other normal variable in ANSI-C.  In
  211. effect, the name in2 is a synonym for the variable named index in
  212. the main program.
  213.  
  214. If you prefer to omit the variable names in the prototypes, you
  215. would write the prototype as follows;
  216.  
  217.    void fiddle(int, int&);
  218.  
  219. If you are a Pascal programmer, you will recognize that the
  220. variable named in1 is treated just like a normal parameter in a
  221. Pascal call, a call by value.  The variable named in2 however, is
  222. treatedlike a variable with the reserved word VAR used in front of
  223. it usually referred to as a call by reference.
  224.  
  225. When you compile and execute this program, you will find that the
  226. first variable got changed in the function but was returned to its
  227. original value when we returned to the main program.  The second
  228. variable however, was changed in the function and the new value was
  229. reflected back into the variable in the main program which we can
  230. see when the values are listed on the monitor.
  231.  
  232.  
  233.  
  234.  
  235.                                                          Page 4-4
  236.  
  237.                                             Chapter 4 - Functions
  238.  
  239. DEFAULT PARAMETERS
  240. _________________________________________________________________
  241.  
  242. Examine the file named DEFAULT.CPP for an         ===============
  243. example of the use of default parameters in C++.    DEFAULT.CPP
  244. This program really looks strange since it        ===============
  245. contains default values for some of the
  246. parameters in the prototype, but these default
  247. values are very useful as we will see shortly.
  248. This prototype says that the first parameter named length must be
  249. given for each call of this function because a default value is not
  250. supplied.  The second parameter named width, however, is not
  251. required to be specified for each call, and if it is not specified,
  252. the value 2 will be used for the variable width within the
  253. function.  Likewise, the third parameter is optional, and if it is
  254. not specified, the value of 3 will be used for height within the
  255. function.
  256.  
  257. In line 11 of this program, all three parameters are specified so
  258. there is nothing unusual about this call from any other function
  259. call we have made.  Only two values are specified in line 12
  260. however, so we will use the default value for the third parameter
  261. and the system acts as if we called it with (x, y, 3) since the
  262. default value for the third value is 3.  In line 13, we only
  263. specified one parameter which will be used for the first formal
  264. parameter, and the other two will be defaulted.  The system will
  265. act as if we had called the function with (x, 2, 3).  Note that the
  266. output from these three lines is reversed.  This will be explained
  267. shortly.
  268.  
  269. There are a few rules which should be obvious but will be stated
  270. anyway.  Once a parameter is given a default value in the list of
  271. formal parameters, all of the remaining must have default values
  272. also.  It is not possible to leave a hole in the middle of the
  273. list, only the trailing values can be defaulted.  Of course, the
  274. defaulted values must be of the correct types or a compiler error
  275. will be issued.  The default values can be given in either the
  276. prototype or the function header, but not in both.  If they are
  277. given in both places, the compiler must not only use the default
  278. value, but it must carefully check to see that both values are
  279. identical.  THis could further complicate an already very
  280. complicated problem, that of writing a C++ compiler.
  281.  
  282.  
  283. WHY IS THE OUTPUT SCRAMBLED?
  284. _________________________________________________________________
  285.  
  286. When the compiler finds a cout statement, the complete line of code
  287. is initially scanned from right to left to evaluate any functions,
  288. then the data is output field by field from left to right. 
  289. Therefore in line 11, get_value() is evaluated with its internal
  290. output displayed first.  Then the fields of the cout are displayed
  291. from left to right with "Some box data is" displayed next. 
  292. Finally, the result of the return from get_value() is output in int
  293.  
  294.                                                          Page 4-5
  295.  
  296.                                             Chapter 4 - Functions
  297.  
  298. format, the type of the returned value.  The end result is that the
  299. output is not in the expected order when lines 11 through 13 are
  300. executed.  (The output is not what you would intuitively expect to
  301. happen so appears to be a deficiency in the language.  A call to
  302. Borland International, the writers of TURBO C++, verified that this
  303. is operating correctly.)
  304.  
  305. Lines 15 through 18 are similar to any two of the lines of code in
  306. lines 11 through 13, but are each separated into two lines so the
  307. output is correct.  
  308.  
  309. Be sure to compile and execute DEFAULT.CPP after you understand it. 
  310. Note that the funny output will appear again later in this
  311. tutorial.
  312.  
  313.  
  314. VARIABLE NUMBER OF ARGUMENTS
  315. _________________________________________________________________
  316.  
  317. Examine the program named VARARGS.CPP for an      ===============
  318. illustration of the use of a variable number of     VARARGS.CPP
  319. arguments in a function call.                     ===============
  320.  
  321. We have gone to a lot of trouble to get the
  322. compiler to help us by carefully checking how many parameters we
  323. use in the function calls and checking the types of the parameters. 
  324. On rare occasion, we may wish to write a function that uses a
  325. variable number of parameters.  The printf() function is a good
  326. example of this.  ANSI-C has a series of three macros available in
  327. the "stdarg.h" header file to allow the use of a variable number
  328. of arguments.  Of course these are available for use with C++ also,
  329. but we need a way to eliminate the strong type checking that is
  330. done with all C++ functions.  The three dots illustrated in line
  331. 6 will do this for us.  This prototype says that a single argument
  332. of type int is required as the first parameter, then no further
  333. checking will be done by the compiler.
  334.  
  335. You will note that the main program consists of three calls to the
  336. function, each with a different number of parameters, and the
  337. system does not balk at the differences in the function calls.  In
  338. fact, you could put as many different types as you desire in the
  339. calls.  As long as the first one is an int type variable, the
  340. system will do its best to compile and run it for you.  Of course
  341. the compiler is ignoring all type checking beyond the first
  342. parameter so it is up to you to make sure you use the correct
  343. parameter types in this call.
  344.  
  345. In this case the first parameter gives the system the number of
  346. additional parameters to look for and handle.  In this simple
  347. program, we simply display the numbers on the monitor to illustrate
  348. that they really did get handled properly.
  349.  
  350. Of course, you realize that using a variable number of arguments
  351. in a function call can lead to very obscure code and should be used
  352.  
  353.                                                          Page 4-6
  354.  
  355.                                             Chapter 4 - Functions
  356.  
  357. very little in a production program, but the capability exists if
  358. you need it.  Be sure to compile and execute this program.
  359.  
  360.  
  361. FUNCTION NAME OVERLOADING
  362. _________________________________________________________________
  363.  
  364. Examine the file named OVERLOAD.CPP for an       ================
  365. example of a program with the function names       OVERLOAD.CPP
  366. overloaded.  This is not possible in ANSI-C, but ================
  367. is perfectly legal and in fact used quite
  368. regularly in C++.  At first this will seem a bit
  369. strange, but it is one of the keystones of object oriented
  370. programming.  You will see its utility and purpose very clearly in
  371. later chapters of this tutorial.
  372.  
  373. You will notice in this example program that there are three
  374. functions, in addition to the main function, and all three have the
  375. same name.  Your first question is likely to be, "Which function
  376. do you call when you call do_stuff()?"  That is a valid question
  377. and the answer is, the function that has the correct number of
  378. formal parameters of the correct types.  If do_stuff() is called
  379. with an integer value or variable as its actual parameter, the
  380. function beginning in line 22 will be called and executed.  If the
  381. single actual parameter is of type float, the function beginning
  382. in line 27 will be called, and if two floats are specified, the
  383. function beginning in line 33 will be called.
  384.  
  385. It should be noted that the return type can also be used to
  386. determine which function will be called, but that is of no help in
  387. this case because the stream output functions called in lines 15
  388. through 19 are typeless as mentioned earlier.
  389.  
  390. The keyword overload used in line 4 tells the system that you
  391. really do intend to overload the name do_stuff, and the overloading
  392. is not merely an oversight.  This is only required in C++ version
  393. 1.2.  C++ version 2.0 and greater do not require the keyword
  394. overload but allows it to be used optionally in order to allow the
  395. existing body of C++ code to be compilable with newer compilers. 
  396. It may be best to include the keyword as an indication to future
  397. readers of your code that function name overloading is
  398. intentionally used here.
  399.  
  400. The actual selection is done at compile time, not at execution time
  401. so the program is not slowed down.  If each of the overloaded
  402. function names were changed to different names, each being unique,
  403. there would be no difference in execution size or time of the
  404. resulting program.
  405.  
  406. Overloading of function names may seem very strange to you , and
  407. it is strange if you are used to the rules of K&R or ANSI-C
  408. programming.  As you gain experience with C++, you will feel very
  409. comfortable with this and you will use it a lot in your C++
  410. programming.
  411.  
  412.  
  413.                                                          Page 4-7
  414.  
  415.                                             Chapter 4 - Functions
  416.  
  417.  
  418. Note the use of the keyword const used in some of the function
  419. prototypes and headers.  Once again, this prevents the programmer
  420. from accidentally changing the formal parameter within the
  421. function.  In a function as short as these, there is no real
  422. problem with an accidental assignment.  In a real function that you
  423. occasionally modify, you could easily forget the original intention
  424. of the use of a value and attempt to change it during an extended
  425. debugging session.
  426.  
  427.  
  428. PROGRAMMING EXERCISES
  429. _________________________________________________________________
  430.  
  431.  
  432. 1.   Change the type of wings in the prototype of PROTYPE1.CPP to
  433.      float so that it disagrees with the function definition to see
  434.      if you get a compilation error.
  435.  
  436. 2.   Change the function definition in PROTYPE1.CPP to agree with
  437.      the changed prototype.  Compile and execute the program
  438.      without changing the calls in lines 12 and 13.  Explain the
  439.      results.
  440.  
  441. 3.   In DEFAULT.CPP, remove the default value from the prototype
  442.      for height only to see what kind of compiler error you get. 
  443.      Only the last values of the list can be defaulted. 
  444.  
  445. 4.   In OVERLOAD.CPP, change the names of the three functions so
  446.      that each is a unique name and compare the size of the
  447.      resulting executable file with that given by the present
  448.      program.
  449.  
  450.  
  451.  
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.  
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.  
  467.  
  468.  
  469.  
  470.  
  471.  
  472.                                                          Page 4-8
  473.